﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HexMerge
{
    public partial class OffsetDialog : Form
    {
        decimal numericUpDownOffsetValue;
        bool moveValid = false;
        int leftOld = 0, topOld = 0;

        public OffsetDialog()
        {
            InitializeComponent();
        }

        private void OffsetDialog_Load(object sender, EventArgs e)
        {
            UpDownBase upDown = (UpDownBase)numericUpDownOffset;
            upDown.TextChanged += new EventHandler(numericUpDownOffset_TextChanged);

            if (moveValid)
            {
                Left = leftOld;
                Top = topOld;
            }
        }

        private void OffsetDialog_FormClosed(object sender, FormClosedEventArgs e)
        {
            leftOld = Left;
            topOld = Top;
            moveValid = true;
        }

        void numericUpDownOffset_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (numericUpDownOffset.Focused)
                {
                    if (checkBoxHex.Checked)
                    {
                        numericUpDownOffsetValue = Convert.ToUInt64(numericUpDownOffset.Text, 16);
                    }
                    else
                    {
                        numericUpDownOffsetValue = Convert.ToDecimal(numericUpDownOffset.Text);
                    }
                }
            }
            catch
            {

            }
        }

        private void numericUpDownOffset_Leave(object sender, EventArgs e)
        {
            if (numericUpDownOffsetValue > numericUpDownOffset.Maximum)
            {
                numericUpDownOffset.Value = numericUpDownOffset.Maximum;
            }
            else if (numericUpDownOffsetValue < numericUpDownOffset.Minimum)
            {
                numericUpDownOffset.Value = numericUpDownOffset.Minimum;
            }
            else
            {
                numericUpDownOffset.Value = numericUpDownOffsetValue;
            }
        }

        private void checkBoxHex_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDownOffset.Hexadecimal = checkBoxHex.Checked;
        }

        public void SetFileName(string name)
        {
            this.Text = "起始地址 - " + name;
        }

        public string GetOffset()
        {
            if (checkBoxHex.Checked)
            {
                return "0x" + ((UInt32)numericUpDownOffset.Value).ToString("X8");
            }
            else
            {
                return numericUpDownOffset.Value.ToString();
            }
        }
    }
}
